package com.blockmeta.bbs.immodule.service;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.blankj.utilcode.util.LogUtils;
import com.blockmeta.bbs.businesslibrary.websocket.SocketIOStatusListener;
import com.blockmeta.bbs.businesslibrary.websocket.WsStatus;

import java.util.List;

import buf.Msg;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;

public class SocketManager implements ISocketManager{

    private String wsUrl;
    private SocketChannel socketChannel;
    private int mCurrentStatus = WsStatus.DISCONNECTED;     //websocket连接状态
    private SocketIOStatusListener socketStatusListener;
    protected int 	 m_nSession;

    public SocketManager(Builder builder) {
        wsUrl = builder.wsUrl;
        m_nSession = builder.session;
    }

    private void initWebSocket(List<SimpleChannelInboundHandler> handlers) {



    }

    @Override
    public SocketChannel getSocket() {
        return socketChannel;
    }


    public void setSocketIOStatusListener(SocketIOStatusListener wsStatusListener) {
        this.socketStatusListener = wsStatusListener;
    }

    @Override
    public synchronized boolean isConnected() {
        return mCurrentStatus == WsStatus.CONNECTED;
    }

    @Override
    public synchronized int getCurrentStatus() {
        return mCurrentStatus;
    }

    @Override
    public synchronized void setCurrentStatus(int currentStatus) {
        this.mCurrentStatus = currentStatus;
    }

    @Override
    public void startConnect() {
        buildConnect();
    }

    @Override
    public void stopConnect() {
        disconnect();
    }


    private void disconnect() {
        if (mCurrentStatus == WsStatus.DISCONNECTED) {
            return;
        }
//        mSocket.disconnect();
//
//        mSocket.off(Socket.EVENT_CONNECT, onConnect);
//        mSocket.off(Socket.EVENT_DISCONNECT, onDisconnect);
//        mSocket.off(Socket.EVENT_CONNECT_ERROR, onConnectError);
//        mSocket.off(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
//        mSocket.off(SOCKET_RESPONSE, onNewMessage);
        setCurrentStatus(WsStatus.DISCONNECTED);
    }

    private synchronized void buildConnect() {
        switch (getCurrentStatus()) {
            case WsStatus.CONNECTED:
            case WsStatus.CONNECTING:
                break;
            default:
                setCurrentStatus(WsStatus.CONNECTING);
//                initWebSocket();
        }
    }

    //发送消息
    @Override
    public boolean sendMessage(Msg.Message msg) {
        boolean isSend = true;
        if (socketChannel != null && mCurrentStatus == WsStatus.CONNECTED) {
            socketChannel.writeAndFlush(msg);
        }
        return isSend;
    }


    //检查网络是否连接
    private boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                LogUtils.i("authorkkk" + "网络正常");
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    public int getSession() {
        return m_nSession;
    }

//    private Emitter.Listener onConnect = new Emitter.Listener() {
//        @Override
//        public void call(Object... args) {
//            setCurrentStatus(WsStatus.CONNECTED);
//            if (socketStatusListener != null) {
//                for (Object o :
//                        args) {
//                    LogUtils.d("author"+ "onConnect"+o.toString());
//                }
//                socketStatusListener.onOpen(getArgsContent(args));
//            }
//        }
//    };
//
//    private Object getArgsContent(Object[] args) {
//        return args.length > 1 ? args[1] : args.length == 1 ? args[0] : args.toString();
//    }
//
//    private Emitter.Listener onDisconnect = new Emitter.Listener() {
//        @Override
//        public void call(Object... args) {
//            if (socketStatusListener != null) {
//                for (Object o :
//                        args) {
//                    LogUtils.d("author"+ "onDisconnect"+o.toString());
//                }
//                socketStatusListener.onClosed(getArgsContent(args));
//            }
//            setCurrentStatus(WsStatus.DISCONNECTED);
//        }
//    };
//
//    private Emitter.Listener onConnectError = new Emitter.Listener() {
//        @Override
//        public void call(Object... args) {
//            if (socketStatusListener != null) {
//                for (Object o :
//                        args) {
//                    LogUtils.d("author"+ "onConnectError"+ o.toString());
//                }
//                socketStatusListener.onFailure(getArgsContent(args));
//                setCurrentStatus(WsStatus.FAIL);
//            }
//        }
//    };
//
//    private Emitter.Listener onNewMessage = new Emitter.Listener() {
//        @Override
//        public void call(final Object... args) {
//            if (socketStatusListener != null) {
//                for (Object o :
//                        args) {
//                    LogUtils.d("author"+ "onNewMessage"+ o.getClass());
//                    if(o.getClass().equals(String.class))
//                    {
//                        LogUtils.d("author"+ "onNewMessage"+ o.toString());
//                    }
//                }
//                socketStatusListener.onMessage(getArgsContent(args));
//            }
//        }
//    };

    public static final class Builder {

        private String wsUrl;
        private int session;


        public Builder wsUrl(String val) {
            wsUrl = val;
            return this;
        }

        public Builder socketSession(int val) {
            session = val;
            return this;
        }

        public SocketManager build() {
            return new SocketManager(this);
        }
    }
}
